package com.aipp.mall.wechat;

import com.aipp.mall.common.model.WechatPhoneNumberInfo;
import com.aipp.mall.common.model.WechatSessionResult;
import com.aipp.mall.common.redis.RedisService;
import com.aipp.mall.common.utils.Json;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cc
 */
@Service
@Slf4j
public class WechatAuthService {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RedisService redisService;
    @Resource
    private WechatPayData wechatPayData;
    private static final String PHONE_INFO = "phone_info";
    private static final String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code";
    private static final String GET_PHONE_NUMBER_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={}";
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={secret}";


    public WechatSessionResult getWechatSession(String code) {
        String url = StrUtil.format(LOGIN_URL, wechatPayData.getMiniProgramAppId(), wechatPayData.getMiniProgramSecret(), code);
        log.info("获取openid，url：{}", url);
        try {
            ResponseEntity<String> res = restTemplate.postForEntity(LOGIN_URL, null, String.class);
            log.info("请求结果{}", res);
            String body = res.getBody();
            if (StrUtil.isEmpty(body)) {
                throw new Exception("获取openid出错");
            }
            return Json.toObj(body, WechatSessionResult.class);
        } catch (Exception e) {
            log.error("获取openid报错", e);
            return null;
        }
    }

    public WechatPhoneNumberInfo getPhoneNumber(String code) {
        try {
            String url = StrUtil.format(GET_PHONE_NUMBER_URL,getAccessToken());
            Map<String, String> params = new HashMap<>();
            params.put("code", code);
            ResponseEntity<String> res = restTemplate.postForEntity(url, params, String.class);
            log.info("请求结果{}", res);
            String body = res.getBody();
            if (StrUtil.isEmpty(body)) {
                throw new Exception("获取openid出错");
            }
            JSONObject jsonObject = JSONUtil.parseObj(body);
            if (jsonObject.containsKey(PHONE_INFO)) {
                Object o = jsonObject.get(PHONE_INFO);
                String str = Json.toStr(o);
                return Json.toObj(str, WechatPhoneNumberInfo.class);
            }
        } catch (Exception e) {
            log.error("获取openid报错", e);
        }
        return null;
    }


    public String getAccessToken() {
        String token = redisService.getWechatToken();
        log.info("redis token：{}", token);
        if (!StrUtil.isEmpty(token)) {
            return token;
        }
        Map<String, String> params = new HashMap<>();
        params.put("appId", wechatPayData.getAppId());
        params.put("secret", wechatPayData.getSecret());
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(GET_ACCESS_TOKEN_URL, String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSONUtil.parseObj(body);
        String accessToken = object.getStr("access_token");
        if (accessToken == null) {
            log.error("获取accessToken失败");
            return null;
        }
        redisService.setWechatToken(accessToken);
        log.info("get token：{}", accessToken);
        return accessToken;
    }

}
